package socketinterface;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import org.eclipse.ui.IViewSite;

import socketinterface.server.RequestSocket;

import com.vast.ui.ledpanel.views.ViewPart;

public class BlockingSocketReceiver extends Thread {
	public  ViewPart     view;
	private Logger       logger;
	private RequestSocket requestSocket;
	private DataInputStream   in = null;
	private DataOutputStream  out = null;
	
	public BlockingSocketReceiver(ViewPart view, RequestSocket requestSocket, Logger logger) {
		this.view          = view;
		this.logger        = logger;
		this.requestSocket = requestSocket;
		
	}
	
	public void openConnection(){
		try {
			in  = new DataInputStream(new BufferedInputStream(requestSocket.getClientSocket().getInputStream()));
			out = new DataOutputStream(new BufferedOutputStream(requestSocket.getClientSocket().getOutputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.writeEntry("Open DataStreamError: " + e.getMessage());	
			e.printStackTrace();
		}
	}
	
	public void closeConnection() {
		try {
			in.close();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.requestSocket.closeClientSocket();
	}

	public void receive(ViewPart view, DataInputStream   in, DataOutputStream   out) {
		ICommandPacket command;
		
		{
			try {
				short   sizeOfPacket = in.readShort();
				short   commandType  = in.readShort();

				switch (commandType) {
					case LedProtocol.PK_LED_UPDATE : {
						command = new UpdateLed(view, in, logger);
						command.execute();
						break;
					}
					case LedProtocol.PK_LED_INITIALIZE : {
						command = new InitializeLed(view, in, logger);
						command.execute();
						break;
					}
					case LedProtocol.PK_COMMAND_TERMINATE : {
						short endMarker = in.readShort();
						logger.writeEntry("Detect terminate command :" + commandType);
						if (endMarker != 0x7FFF) {
							logger.writeEntry("EndMarker is broken. : EndMarker = 0x" + Integer.toHexString((int)endMarker) + " (" + Integer.toString((int)endMarker) + ")");
						}
						closeConnection();
						break;
					}
					default : logger.writeEntry("Unknown command :" + commandType); return;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				
				return;
			}
		}
	}

	public void run() {
		// TODO Auto-generated method stub
		openConnection();
		
		while (!requestSocket.isClosed()) {
			receive(view, in, out);
		}
	}
}
